package com.acme.cli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {

    private static final String UNKNOWN_HOST_EXCEPTION_MESSAGE =
            "You are trying to connect to an unknown host!";
    private static final String INVALID_DATA_EXCEPTION_MESSAGE =
            "Data received in unknown format";

    private static final String STOP_SERVER_COMMAND = "bye";

    private static final String HOST = "localhost";
    private static final int PORT = 2004;

    private Socket requestSocket;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private String message;

    void run() {
        try {
            requestSocket = new Socket(HOST, PORT);
            System.out.println("Connected to " + HOST + " in port " + PORT);
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(System.in));
            do {
                message = receiveMessage();
                message = reader.readLine();
                sendMessage(message);
            } while (!message.equals(STOP_SERVER_COMMAND));
        } catch (UnknownHostException e) {
            System.err.println(UNKNOWN_HOST_EXCEPTION_MESSAGE);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
                requestSocket.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    void sendMessage(final String msg) {
        try {
            out.writeObject(msg);
            out.flush();
            System.out.println("client> " + msg);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    String receiveMessage() {
        String s = null;
        try {
            s = (String) in.readObject();
            System.out.println("server> " + s);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (ClassNotFoundException e) {
            System.err.println(INVALID_DATA_EXCEPTION_MESSAGE);
        }
        return s;
    }

    public static void startClient() {
        BankClient client = new BankClient();
        client.run();
    }

    public static void main(final String[] args) {
        startClient();
    }

}
